package com.atfusu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Title:用于配置SpringSecurity
 * Author: fusu
 * DateTime:  2022/12/5
 * Description:
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 设置在内存中存入一个临时账号用于测试
     * 注意：需要设置加密方式
     */
    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("");
    }*/

    /**
     * 指定加密方式，并将对象放入ioc容器内
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 设置允许iframe嵌套显示页面
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //目前必须调用父类方法，否则验证失效
//        super.configure(http);
        //允许iframe多级嵌套使用
        http.headers().frameOptions().disable();
        //允许iframe单级显示
//        http.headers().frameOptions().sameOrigin();

        //登录设置
        http.authorizeRequests()
                .antMatchers("/static/**", "/login").permitAll()//允许匿名访问的路径
                .anyRequest().authenticated();//其他页面需要验证登录

        http.formLogin()
                .loginPage("/login")//设置自己的登录页面
                .defaultSuccessUrl("/");//登录成功后，默认的跳转页面

        http.logout()
                .logoutUrl("/logout")//设置登出的路径，指定spring security拦截的注销url
                .logoutSuccessUrl("/login");//指定用户退出后，重定向的页面

        http.csrf().disable(); //关闭跨域请求伪造功能

        //添加无权限处理器
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeineHandler());
    }
}
